<template>
  <aside class="patient-sidebar" :class="{ collapsed: isCollapsed }">
    <InfoHeader title="患者列表" :show-collapse="true" :collapsed="isCollapsed" @toggle-collapse="toggleCollapse" />
    <div class="patient-list">
      <el-radio-group v-model="selectedPatientType" class="patient-type-selector">
        <el-radio label="myPatients">我的患者</el-radio>
        <el-radio label="otherPatients">其他患者</el-radio>
      </el-radio-group>

      <div class="patient-list-content">
        <div v-if="selectedPatientType === 'otherPatients'" class="search-bar">
          <el-select v-model="searchBed" placeholder="床位" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="bed in bedOptions" :key="bed" :label="bed" :value="bed" />
          </el-select>
          <el-select v-model="searchStatus" placeholder="状态">
            <el-option label="在科" value="in" />
            <el-option label="出院" value="out" />
            <el-option label="转科" value="transfer" />
          </el-select>
          <el-select v-model="searchCaseNo" placeholder="病案号" clearable filterable>
            <el-option v-for="patient in props.patients.otherPatients" :key="patient.id" :label="patient.id"
              :value="patient.id" />
          </el-select>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </div>
        <ul class="patient-ul">
          <li
            v-for="(patient, index) in (selectedPatientType === 'myPatients' ? props.patients.myPatients : props.patients.otherPatients)"
            :key="patient.id" class="patient-item" :class="{ active: index === activePatientIndex }"
            @click="selectPatient(index)">
            <div class="patient-line first-line">
              <span class="bed-number">{{ patient.bedNumber }}</span>
              <span class="admission-time">入科 {{ patient.admissionDate }}</span>
            </div>
            <div class="patient-line">
              <span class="name">{{ patient.name }}</span>
              <span class="gender">{{ patient.gender }}</span>
              <span class="age">{{ patient.age }}岁</span>
            </div>
            <div class="patient-line">
              <span class="patient-id">{{ patient.id }}</span>
            </div>
            <div class="patient-line diagnosis-line">
              <el-icon>
                <Document />
              </el-icon>
              <span class="diagnosis">{{ patient.diagnosis }}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <InfoHeader title="提醒事项" @click="showReminderDialog = true" />
    <div class="reminder-section handover-section">
      <div class="section">
        <el-table :key="'reminder-' + activePatientIndex" :data="reminderDetails" border style="width: 100%"
          :show-header="false">
          <el-table-column prop="category" label="分类" show-overflow-tooltip></el-table-column>
          <el-table-column prop="item" label="项目" show-overflow-tooltip></el-table-column>
          <el-table-column prop="result" label="结果" width="90" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog v-model="showReminderDialog" title="提醒事项详情" width="50%">
      <el-table :data="reminderDetails" border style="width: 100%">
        <el-table-column prop="category" label="分类" show-overflow-tooltip />
        <el-table-column prop="item" label="项目" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="result" label="结果" width="90" show-overflow-tooltip />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="handleReminderAction(scope.row)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog v-model="showHandoverDialog" title="交班事项详情" width="50%">
      <el-table :data="handoverDetails" border style="width: 100%">
        <el-table-column prop="category" label="分类" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="90" show-overflow-tooltip />
      </el-table>
    </el-dialog>


    <InfoHeader title="交班事项" @click="showHandoverDialog = true" />
    <div class="handover-section">
      <div class="section">
        <el-table :data="handoverDetails" border style="width: 100%" :show-header="false">
          <el-table-column prop="category" label="分类" show-overflow-tooltip></el-table-column>
          <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
          <el-table-column prop="status" label="状态" width="90" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
    </div>


    <InfoHeader title="护理工具栏" @click="showNursingDialog = true" />
    <div class="nursing-toolbar">
      <div class="chat-container">
        <div class="chat-messages" ref="chatMessages">
          <div v-for="(msg, index) in chatMessages" :key="index" class="message">
            <span class="sender">{{ msg.sender }}:</span>
            <span class="content">{{ msg.content }}</span>
          </div>
        </div>
        <div class="chat-input">
          <el-input v-model="newMessage" placeholder="输入消息..." @keyup.enter="sendMessage" />
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
    </div>

    <el-dialog v-model="showNursingDialog" title="医护互动" width="45%">
      <div class="nursing-dialog-content">
        <div class="chat-messages" ref="nursingMessages" style="min-height: 500px;">
          <div v-for="(msg, index) in nursingMessages" :key="index" class="message">
            <span class="sender">{{ msg.sender }}:</span>
            <span class="content">{{ msg.content }}</span>
            <img v-if="msg.image" :src="msg.image" class="message-image" />
            <audio v-if="msg.audio" controls :src="msg.audio"></audio>
          </div>
        </div>
        <div class="chat-input" style="margin-bottom: 20px;">
          <el-input v-model="nursingMessage" placeholder="输入消息..." @keyup.enter="sendNursingMessage" />
          <el-button type="primary" @click="sendNursingMessage">发送</el-button>
        </div>
        <div class="nursing-tools" style="margin-top: 20px;">
          <el-button @click="startVideoCall">视频</el-button>
          <el-button @click="takePhoto">拍摄</el-button>
          <el-button @click="uploadImage">图片</el-button>
          <el-button @click="startRecording">{{ isRecording ? '停止录音' : '开始录音' }}</el-button>
          <el-button @click="sendNotification">一键通知</el-button>
          <el-button @click="uploadMedicalRecord">语音病历</el-button>
        </div>
      </div>
    </el-dialog>
  </aside>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, watch } from 'vue'
import InfoHeader from './InfoHeader.vue'
import { ElRadioGroup, ElRadio, ElIcon, ElSelect, ElOption, ElButton } from 'element-plus'
import { Document, Search, Menu } from '@element-plus/icons-vue'

interface Patient {
  id: string
  name: string
  bedNumber: string
  admissionDate: string
  gender: string
  age: number
  diagnosis: string
}

interface Props {
  patients: {
    myPatients: Patient[]
    otherPatients: Patient[]
  }
  reminders: string[]
  handovers: string[]
}

const props = defineProps<Props>()

const isCollapsed = ref(false)
const selectedPatientType = ref<'myPatients' | 'otherPatients'>('myPatients')

watch(selectedPatientType, () => {
  refreshRemindersAndHandovers()
})
const selectedPatient = ref<Patient | null>(null)
const activePatientIndex = ref(0)
const searchBed = ref('')
const searchStatus = ref('in')
const searchCaseNo = ref('')

const bedOptions = computed(() => {
  return Array.from(new Set(props.patients.otherPatients.map(p => p.bedNumber)))
})

const toggleCollapse = (): void => {
  isCollapsed.value = !isCollapsed.value
}

const selectPatient = (index: number): void => {
  activePatientIndex.value = index
  const patients = selectedPatientType.value === 'myPatients'
    ? props.patients.myPatients
    : props.patients.otherPatients
  selectedPatient.value = patients[index]

  // 强制清空数组再重新填充
  reminderDetails.value.length = 0
  reminderDetails.value.push(
    {
      category: '用药',
      item: '抗生素',
      content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})需要静脉注射头孢曲松钠2g q12h`,
      result: '待执行'
    },
    {
      category: '检查',
      item: 'CT扫描',
      content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})需要做胸部CT平扫`,
      result: '已预约'
    },
    {
      category: '护理',
      item: '换药',
      content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})伤口需要每日换药`,
      result: '已完成'
    }
  )

  // 更新交班事项数据
  handoverDetails.value = props.handovers.map(item => {
    const parts = item.split('|')
    return {
      category: parts[0] || '未分类',
      content: `${selectedPatient.value?.name}(${selectedPatient.value?.bedNumber}): ${parts[1] || '无内容'}`,
      status: parts[2] || '未处理'
    }
  })
}

const refreshRemindersAndHandovers = () => {
  const patients = selectedPatientType.value === 'myPatients'
    ? props.patients.myPatients
    : props.patients.otherPatients

  // 自动选中第一个患者
  if (patients.length > 0) {
    activePatientIndex.value = 0
    selectedPatient.value = patients[0]
  }

  if (selectedPatient.value) {
    // 更新提醒事项数据
    reminderDetails.value = [
      {
        category: '用药',
        item: '抗生素',
        content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})需要静脉注射头孢曲松钠2g q12h`,
        result: '待执行'
      },
      {
        category: '检查',
        item: 'CT扫描',
        content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})需要做胸部CT平扫`,
        result: '已预约'
      },
      {
        category: '护理',
        item: '换药',
        content: `${selectedPatient.value.name}(${selectedPatient.value.bedNumber})伤口需要每日换药`,
        result: '已完成'
      }
    ]

    // 更新交班事项数据
    handoverDetails.value = props.handovers.map(item => {
      const parts = item.split('|')
      return {
        category: parts[0] || '未分类',
        content: `${selectedPatient.value?.name}(${selectedPatient.value?.bedNumber}): ${parts[1] || '无内容'}`,
        status: parts[2] || '未处理'
      }
    })
  }
}

const handleSearch = () => {
  console.log('Search params:', {
    bed: searchBed.value,
    status: searchStatus.value,
    caseNo: searchCaseNo.value
  })
  refreshRemindersAndHandovers()
}

// 聊天功能
const chatMessages = ref<Array<{ sender: string, content: string }>>([])
const newMessage = ref('')
const socket = ref<WebSocket | null>(null)

onMounted(() => {
  // 连接到局域网WebSocket服务器
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  socket.value = new WebSocket(`${protocol}//${host}/chat`)

  socket.value.onmessage = (event) => {
    const data = JSON.parse(event.data)
    chatMessages.value.push(data)
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket error:', error)
  }
})

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close()
  }
})

const sendMessage = () => {
  if (newMessage.value.trim() && socket.value?.readyState === WebSocket.OPEN) {
    const message = {
      sender: '护士工作站',
      content: newMessage.value.trim()
    }
    socket.value.send(JSON.stringify(message))
    chatMessages.value.push(message)
    newMessage.value = ''
  }
}

interface ReminderDetail {
  category: string
  item: string
  content: string
  result: string
}

const showReminderDialog = ref(false)
const reminderDetails = ref<ReminderDetail[]>([
  {
    category: '用药',
    item: '抗生素',
    content: '患者A需要静脉注射头孢曲松钠2g q12h',
    result: '待执行'
  },
  {
    category: '检查',
    item: 'CT扫描',
    content: '患者B需要做胸部CT平扫',
    result: '已预约'
  },
  {
    category: '护理',
    item: '换药',
    content: '患者C伤口需要每日换药',
    result: '已完成'
  }
])

const handleReminderAction = (row: ReminderDetail) => {
  console.log('处理提醒事项:', row)
  // 这里可以添加实际的处理逻辑
}

interface HandoverDetail {
  category: string
  content: string
  status: string
}

const showHandoverDialog = ref(false)
const handoverDetails = ref<HandoverDetail[]>([])

// 医护互动功能
interface NursingMessage {
  sender: string
  content: string
  image?: string
  audio?: string
}

const showNursingDialog = ref(false)
const nursingMessages = ref<NursingMessage[]>([])
const nursingMessage = ref('')
const isRecording = ref(false)
const nursingSocket = ref<WebSocket | null>(null)

const startVideoCall = () => {
  console.log('启动视频通话')
  // 实际视频通话实现
}

const takePhoto = () => {
  console.log('拍照')
  // 实际拍照实现
}

const uploadImage = () => {
  console.log('上传图片')
  // 实际图片上传实现
}

const startRecording = () => {
  isRecording.value = !isRecording.value
  console.log(isRecording.value ? '开始录音' : '停止录音')
  // 实际录音实现
}

const sendNotification = () => {
  console.log('发送一键通知')
  // 实际通知实现
}

const uploadMedicalRecord = () => {
  console.log('上传语音病历')
  // 实际病历上传实现
}

const sendNursingMessage = () => {
  if (nursingMessage.value.trim()) {
    const message = {
      sender: '护士工作站',
      content: nursingMessage.value.trim()
    }
    nursingMessages.value.push(message)
    nursingMessage.value = ''
  }
}

onMounted(() => {
  // 连接到医护互动WebSocket服务器
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  nursingSocket.value = new WebSocket(`${protocol}//${host}/nursing`)

  nursingSocket.value.onmessage = (event) => {
    const data = JSON.parse(event.data)
    nursingMessages.value.push(data)
  }

  nursingSocket.value.onerror = (error) => {
    console.error('医护互动WebSocket错误:', error)
  }
})

onBeforeUnmount(() => {
  if (nursingSocket.value) {
    nursingSocket.value.close()
  }
})
</script>

<style scoped>
.nursing-toolbar {
  padding: 10px;
  background: var(--bg);
}

.chat-container {}

.chat-messages {
  height: 200px;
  overflow-y: auto;
  border: 1px solid var(--border-color);
  padding: 8px;
  margin-bottom: 8px;
  background: white;
}

.message {
  margin-bottom: 5px;
  font-size: 13px;
}

.message .sender {
  font-weight: bold;
  margin-right: 5px;
}

.chat-input {
  display: flex;
  gap: 8px;
}

.chat-input .el-input {
  flex: 1;
}

.patient-sidebar {
  width: 300px;
  border-right: 1px solid var(--border-color);
  transition: all 0.3s ease;
  position: relative;
  background-color: var(--primary-bg);
  color: var(--text);
  padding: 0 4px;
}

.patient-sidebar.collapsed {
  width: 50px;
  overflow: hidden;
}

.patient-sidebar.collapsed .patient-list,
.patient-sidebar.collapsed .reminder-section,
.patient-sidebar.collapsed .handover-section,
.patient-sidebar.collapsed .nursing-toolbar {
  display: none;
}

.patient-sidebar.collapsed .info-header {
  justify-content: center;
  padding: 0;
  height: 36px;
}

.patient-sidebar.collapsed .info-header h3,
.patient-sidebar.collapsed .info-header .el-button span,
.patient-sidebar.collapsed .info-header .el-button::after {
  display: none !important;
  visibility: hidden !important;
}

.patient-sidebar.collapsed .info-header .el-button {
  margin: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.patient-sidebar.collapsed .info-header .el-icon {
  font-size: 20px;
  margin: 0;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 0 4px;
  background-color: var(--primary-bg);
  height: 36px;
}

.info-header .el-button {
  padding: 0;
  margin-left: 8px;
}

.info-header .el-icon {
  font-size: 16px;
  color: var(--text-secondary);
}

.info-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: var(--text-secondary);
}

.patient-list {
  padding: 5px;
  background: var(--bg);
  height: 30%;
  overflow-y: auto;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
  position: relative;
}

.patient-type-selector {
  position: sticky;
  top: 0;
  z-index: 10;
  background: var(--bg);
  padding: 0;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 2px;
  display: flex;
  align-items: center;
  height: 24px;
}

.patient-type-selector .el-radio {
  display: flex;
  align-items: center;
  height: 100%;
}

.patient-list::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari and Opera */
}

.patient-list-content {
  height: 100%;
  overflow-y: auto;
}

.patient-type-selector {
  width: 100%;
  display: flex;
  gap: 10px;
}

.patient-type-selector .el-radio {
  flex: 1;
  margin-right: 0;
  display: flex;
  justify-content: center;
}

.patient-type-selector .el-radio__label {
  font-size: 12px;
  color: var(--text);
}

.patient-type-selector .el-radio.is-checked .el-radio__label {
  color: var(--el-color-primary);
}

.search-bar {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto;
  gap: 8px;
  margin-bottom: 12px;
}

.search-bar .el-select {
  width: 100%;
}

.search-bar .el-select:nth-child(3) {
  /* 病案号选择框 */
  grid-column: 1;
  grid-row: 2;
  width: calc(200% - 60px);
  /* 减去按钮宽度和间距 */
}

.search-bar .el-button {
  grid-column: 2;
  grid-row: 2;
  width: 60px;
  justify-self: end;
}

.patient-ul {
  list-style: none;
  padding-left: 0px;
  width: 100%;
}

.patient-item {
  padding: 4px 2px;
  border: 1px solid var(--border-color);
  margin-bottom: 5px;
  cursor: pointer;
}

.patient-item.active {
  background-color: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);

}

.patient-line {
  display: flex;
  align-items: center;
  margin: 4px 0;
  font-size: 12px;
  color: var(--text);
}

.first-line {
  justify-content: space-between;
}

.bed-number {
  font-weight: bold;
  font-size: 18px;
  color: var(--el-color-primary);
}

.name {
  margin-right: 8px;
  font-weight: bold;
  font-size: 15px;
}

.gender,
.age {
  margin-right: 8px;
}

.patient-id {
  font-size: 14px;
  font-weight: bold;
}

.diagnosis {
  font-weight: bold;
  font-size: 15px;
}

.diagnosis-line .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.reminder-section {
  padding: 0;
  background: var(--bg);
}

/* 确保表格容器不会溢出 */
.reminder-section .section {
  overflow: hidden;
  width: 100%;
}

.section {
  margin-top: 0;
}

.section h3 {
  margin-bottom: 8px;
  font-size: 14px;
}

.section ul {
  list-style: none;
  padding-left: 10px;
}

.section li {
  padding: 4px 0;
  font-size: 13px;
}

/* 统一表格样式 */
.reminder-section .el-table,
.handover-section .el-table {
  font-size: 12px;
}

.reminder-section .el-table td,
.handover-section .el-table td {
  padding: 1px 0;
}

.reminder-section .el-table .cell,
.handover-section .el-table .cell {
  line-height: 1;
  padding: 0 4px;
}

.reminder-section .el-table--border td,
.handover-section .el-table--border td {
  border-bottom-width: 1px;
}
</style>
